package com.cn.jasyptdbtwo.util;


import org.apache.commons.codec.binary.Base64;

import java.nio.charset.StandardCharsets;

/**
 * @ClassName ByteUtil
 * @Description: TODO
 * @Author xiaojiang
 * @Date 2021/3/11 下午 14:24
 * @Version 1.0
 **/
public class ByteUtil {

    public static byte[] toBytes(String str) {  //  aa  -->  0xaa
        if (str == null || "".equals(str.trim())) {
            return new byte[0];
        }

        byte[] bytes = new byte[str.length() / 2];
        for (int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
//            System.out.println("shuju=" + subStr);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }

        return bytes;
    }

    /**
     * @Description: 第一种 byte[]转String
     * @date 2021/3/11 下午 14:31
     */
    public static String toHexString1(byte[] b) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < b.length; ++i) {
            buffer.append(toHexString1(b[i]));
        }
        String str = buffer.toString().substring(0, buffer.length());
        return str;
    }

    public static String toHexString1(byte b) {
        String s = Integer.toHexString(b & 0xFF);
        if (s.length() == 1) {
            return "0" + s;
        } else {
            return s ;
        }
    }
    
    /**
     * @Description: 第一种 byte[]转String带，
     * @date 2021/3/11 下午 14:31
     */
      public static String toHexString2(byte[] b) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < b.length; ++i) {
            buffer.append(toHexString2(b[i]));
        }
        String str = buffer.toString().substring(0, buffer.length() - 1);
        return str;
    }

    public static String toHexString2(byte b) {
        String s = Integer.toHexString(b & 0xFF);
        if (s.length() == 1) {
            return "0" + s + ",";
        } else {
            return s + ",";
        }
    }

    /**
     * TODO base64编码
     *
     * @date 2021/9/10 下午 17:04
     */
    public static String encodeBase64(byte[] source) {
        return new String(Base64.encodeBase64(source), StandardCharsets.UTF_8);
    }

    /**
     * TODO Base64解码
     *
     * @date 2021/9/10 下午 17:04
     */
    public static byte[] decodeBase64(String target) {
        return Base64.decodeBase64(target.getBytes(StandardCharsets.UTF_8));
    }

    public static void main(String[] args)  throws Exception{
        String test = "SQABAAVXAAkClwKQDCSsFDlR";
        System.out.println("原数据：" + test);
        byte[] bytes = decodeBase64(test);


        String s = ByteUtil.toHexString1(bytes);
        System.out.println("解密后：" + s);

        String s1 = encodeBase64(toBytes(s));
        System.out.println("加密后：" + s1);


    }



}
